
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">



<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="static/css/fullcalendar.min.css"
	rel='stylesheet' />
<link rel="stylesheet" href="static/css/fullcalendar.print.min.css"
	rel='stylesheet' media='print' />
<link rel="stylesheet" href="static/css/jquery-ui.css" rel='stylesheet' />
<link rel="stylesheet" href="static/css/bootstrap.min.css" rel='stylesheet' />
<script type="text/javascript" src="static/js/moment-with-locales.js"
	charset="UTF-8"></script>
<script type="text/javascript" src="static/js/jquery-3.2.1.min.js"
	charset="UTF-8"></script>
<script type="text/javascript" src="static/js/jquery-ui.js" charset="UTF-8"></script>
<script type="text/javascript" src="static/js/bootstrap.min.js" charset="UTF-8"></script>
<script src="static/js/fullcalendar.min.js" charset="UTF-8"></script>
<title>会议室管理</title>
<style>
body {
	margin: 0;
	font-family: "Lucida Grande", Helvetica, Arial, Verdana, sans-serif;
	font-size: 14px;
	padding-top: 70px;
}

#top {
	background: #eee;
	border-bottom: 1px solid #ddd;
	padding: 0 10px;
	line-height: 40px;
	font-size: 12px;
}

#calendar {
	max-width: 900px;
	margin: 40px auto;
	padding: 0 10px;
}
/*控制背景色的样式*/
#title{
    background-color : blue;
    color : black;
    /*控制标题栏的左内边距*/
}
#cotent{
    padding-left : 3px;
    padding-top :  5px;
    background-color : blue;
    
}
/*控制关闭按钮的位置*/
#close{
    margin-left: 188px;
    /*当鼠标移动到X上时，出现小手的效果*/
    cursor: pointer;
} */
.hidden{
        display: none;
        }
        
table td.dselected {
    background-color: green;
}

table td.mlimit {
    background-color: red;
}
</style>
<script type="text/javascript">
var startCellIndex = null;
var startCellTime = null;
var endCellTime = null;
var cellRoomId = null;
var cellRoomName = null;
var duration=null;
var now = new Date();
var year = now.getFullYear();
var month = now.getMonth() + 1;
var day = now.getDate();
var selectday = null;
	$(function() {
		//定义模态框数据
		var tableStr =  $('#tableDiv').html();
		$('#tableDiv').html('');
	    var modalDataArray = new Array(tableStr, $('#deviceDiv').html());
	    moadlDataControl("#myModal", modalDataArray, modalCallback);
		var initialLocaleCode = 'zh-cn';
		var showDialogAction = function(options) {
			var pattern = '/my/calendars/events/:id/dialog';
			for (key in options) {
				var val = options[key];
				pattern = pattern.replace(':' + encodeURIComponent(key),
						((val === undefined || val === null) ? '' : val));
			}
			return pattern;
		};
		$('#calendar').fullCalendar(
				{
					header : {
						left : 'prev,next today',
						center : 'title',
						right : 'month,agendaWeek,agendaDay,listMonth'
					},
				    buttonText: {
				        today: '今天',
				        month: '月',
				        agendaWeek: '周',
				        agendaDay: '日',
				        listMonth: '月视图',
				        prev:'上月',
				        next:'下月'
				    },
					defaultDate : year + '-' + month + '-' + day,
					minTime : now.getHours() + ':' + now.getMinutes() + ':'
							+ now.getSeconds(),
					defaultTimedEventDuration : '01:00:00',
					locale : initialLocaleCode,
					buttonIcons : false, // show the prev/next text
					navLinks : true, // can click day/week names to navigate views
					editable : false,
					eventLimit : true, // allow "more" link when too many events
					selectable : true,
					selectHelper : true,
					selectOverlap : false,
					dayClick : function(date, allDay, jsEvent, view) { // 定义了点击日历中日期格子的动作，这里将会调用jQueryUi的dialog生成创建新日历项的对话框
						$('#myModal').modal({
							keyboard: true
						}); 
						tableAction();
						var table = $("#meetingRoomsTable");
						selectday=new Date(date);
						var selectDate = selectday.getFullYear()+ '-' +(selectday.getMonth() + 1)+ '-' ;
						$.get('<%=request.getContextPath()%>/form/queryMeeting.do',{"start":selectDate+selectday.getDate(),"end":selectDate+(selectday.getDate()+1),"_":Math.random()}, function (data) {
					    	$.each(JSON.parse(data), function (n, value) {
				               var start = value.start;
				               var end = value.end;
				               var startTime = start.substr(start.indexOf(" ")+1,5);
				               var endTime = end.substr(end.indexOf(" ")+1,5);
				               var rowStart = table.find("tr[data-room-name='"+value.place+"']").index();
				               var startind ;//= table.find("tr").eq(rowStart).find("td[data-time='"+startTime+"']").index();
				               var endind ;//= table.find("tr").eq(rowStart).find("td[data-time='"+endTime+"']").index();
				               table.find("tr").eq(rowStart).find("td").each(function(i){
				                   if($(this).data('time')==startTime)
				                   {
				                	   startind=i;
				                   }else if($(this).data('time')==endTime){
					                   endind=i;
					               }
				                   
				               })
				               for (var j = startind; j <= endind; j++) {
				            	   console.log(table.find("tr").eq(rowStart).find("td[data-time='"+startTime+"']").index());
				            	   table.find("tr").eq(rowStart).find("td").eq(j).addClass("mlimit");
				   	           }
				            });
					    	$('.mlimit').each(function() {
						    });
						});
						/* var openNewLink = window.open('http://localhost:8080/meeting/add.do', '预定会议室', 'height=300, width=400, top=0, left=0, toolbar=no, menubar=no, scrollbars=no, resizable=false, location=no, status=no'); //参数： url, 名称, 窗体样式
				        if(window.focus) {
				          openNewLink.focus();
				        } */
					},
					eventClick : function(calEvent, jsEvent, view) {
						$('#hiddenid').val(calEvent.id);
						$.get('<%=request.getContextPath()%>/form/queryDetail.do',{"id": calEvent.id}, function (data) {
						    $('#meeting-content').html(data);
						    $('#modal-event').modal();
						});
						/* $.get(showDialogAction({id: calEvent.id}), function (data) {
						    $('#meeting-content').html(data);
						    $('#modal-event').modal();
						});  */
					},
					events : '<%=request.getContextPath()%>/form/queryMeeting.do'
				});
	    $('#btn-change-day').datepicker({format: 'yyyy-mm-dd'}).
	    on('changeDate.datepicker.amui', function (event) {
	        location.href='/meetings/d/' + $('#btn-change-day').data('date') + '/r/FUvz9bSR58DdAxNKHZfJpY';
	    });

	    $('.busy').click(function () {
	        location.href = $(this).data('href');
	    });

	    // 可预订
	    $('.mavailab').click(function(){
	                        // 弹框选择会议类型
	    });
	    $('body').append('<div class="am-popover am-popover-top" style="opacity:1;white-space: nowrap" id="am-popover-order"><div class="am-popover-inner"></div><div class="am-popover-caret"></div></div>');
	    //tableAction();

	    

	});
	
	function tableAction(){
		var table = $("#meetingRoomsTable");
	    $('#meetingRoomsTable .mavailab').hover(function() {
	        $('#am-popover-order .am-popover-inner').text('双击或拖动选择预订' + $(this).data('time') + $(this).parent().data('room-name'));
	        var thisOffsetLeft = $(this).offset().left;
	        var popoverWidth = $('#am-popover-order').outerWidth();
	        var offsetLeft = thisOffsetLeft + (popoverWidth/2 - $(this).outerWidth()/2 + 10) > $('body').width() - 20 ? $('body').width() - popoverWidth - 5: thisOffsetLeft - popoverWidth/2 + $(this).outerWidth()/2
	        $('#am-popover-order').css({
	            left: offsetLeft,
	            top: $(this).offset().top - 52
	        })
	        $('#am-popover-order').show();
	    }, function() {
	        $('#am-popover-order').hide();
	    });

	    


	    // 时间选择
	    

	    var isMouseDown = false;
	    var startRowIndex = null;
	    

	    function selectTo(cell) {

	        var row = cell.parent();
	        var cellIndex = cell.index();
	        var rowIndex = row.index();

	        var rowStart, rowEnd, cellStart, cellEnd;
			
	        rowStart = startRowIndex;
	        rowEnd = rowIndex;
	        var rowCells = table.find("tr").eq(rowStart).find("td");
	        if (cellIndex < startCellIndex) {
	            cellStart = cellIndex;
	            cellEnd = startCellIndex;
	        } else {
	            cellStart = startCellIndex;
	            cellEnd = cellIndex;
	        }

	        endCellTime = cell.data('time');
	        cellRoomId = cell.parent().data('room-id');
	        cellRoomName = cell.parent().data('room-name');
	        
	        for (var j = cellStart; j <= cellEnd; j++) {
	            rowCells.eq(j).addClass("dselected");
	        }

	    }

	    table.find("td.meeting-cell").mousedown(function (e) {
            isMouseDown = true;
            var cell = $(this);
			
            table.find(".dselected").removeClass("dselected"); // deselect everything

            if (e.shiftKey) {
                selectTo(cell);
            } else {
            	if(cell.hasClass('mlimit')){
    				alert("该会议室此时间已经预订！请重新选择！");
    				isMouseDown=false;
    				return;
    			}
                cell.addClass("dselected");
                startCellIndex = cell.index();
                startRowIndex = cell.parent().index();
                startCellTime = cell.data('time');
                endCellTime = cell.data('time');
                cellRoomName = cell.parent().data('room-name');
            }

            return false; // prevent text selection
        })
        .mouseover(function () {
            if (!isMouseDown) return;
            selectTo($(this));
        })
        .bind("selectstart", function () {
            return false;
        });
	    
	    $(document).mouseup(function () {
	        if (isMouseDown) {
	        	//endCellTime =  $(this).data('time');
	            // 检查选择的时间段
	            var dStart = new Date(year+'-'+month+'-'+day+' ' + startCellTime + ':00');
	            var dEnd = new Date(year+'-'+month+'-'+day+' ' + endCellTime + ':00');
	            //alert(year+'-'+month+'-'+day+'T' + startCellTime + ':00'+"~"+year+'-'+month+'-'+day+'T' + endCellTime + ':00');
	            //alert(dStart+'~'+dEnd);
	            duration = (dEnd.getTime() - dStart.getTime()) / 60000 + 30;
	            if (duration > 720) {
	                duration = 60;
	            }

	            if (startCellTime== undefined) {
	                isMouseDown = false;
	                return;
	            }
	            if (cellRoomName == undefined) {
	                isMouseDown = false;
	                return;
	            }
				//alert(cellRoomName+"~~"+startCellTime+"~~"+endCellTime+ '&duration=' + duration);
	                                // 弹框选择会议类型
	                // TODO:  不存在, 改js
	                /* $('#dlg-new-meeting-title').html('预订2017-11-30' + cellRoomName + startCellTime);
	                $('#dlg-new-meeting-link-s').attr('href', '/meetings/d/2017-11-30/r/' + cellRoomId + '/new?startTime=' + startCellTime +  '&duration=' + duration);
	                                        $('#dlg-new-meeting-link-i').attr('href', '/meetings/d/2017-11-30/r/' + cellRoomId + '/new-interview?startTime=' + startCellTime + '&duration=' + duration);
	                                                            $('#dlg-new-meeting-link-c').attr('href', '/meetings/d/2017-11-30/r/' + cellRoomId + '/new-customer?startTime=' + startCellTime + '&duration=' + duration); */
	                                   // $('#new-meeting-dlg').modal({width: "280px"});
	                                        }
	        isMouseDown = false;
	    });
	}
	
	function addMeeting(persons){
		
		 $.post("<%=request.getContextPath()%>/form/addMeeting.do",{"place":cellRoomName,"meetingname":cellRoomName+startCellTime+duration,"duration":duration,"startTime":selectday.getFullYear()+'-'+(selectday.getMonth()+1)+'-'+selectday.getDate()+' ' + startCellTime + ':00',"endTime":selectday.getFullYear()+'-'+(selectday.getMonth()+1)+'-'+selectday.getDate()+' ' + endCellTime + ':00',"persons":persons},function(result){
		        if(result=="suc"){
		        	$('#myModal').modal('hide');
		        	$('#calendar').fullCalendar('refetchEvents');
		        }else{
		        	alert("预订会议室失败，请重试！");
		        }
		    });
	}
	
	function deleteMeeting(){
		 $.post("<%=request.getContextPath()%>/form/delMeeting.do",{"id":$('#hiddenid').val()},function(result){
		        if(result=="suc"){
		        	$('#modal-event').modal('hide');
		        	$('#calendar').fullCalendar('refetchEvents');
		        }else{
		        	alert("预订会议室失败，请重试！");
		        }
		  });
	}
	
	/**
	 *
	 * @param modalSelect modal选择符，本例为“#myModal”
	 * @param modalDataArray html代码字符串数组
	 * @param currentPageIndex 当前页码
	 * @param direction 1表示下一页方向，-1表示上一页方向
	 */
	function controlPageToggle(modalSelect, modalDataArray, currentPageIndex, direction) {
	    var arrayLength = modalDataArray.length;
	    if (arrayLength <= 1)
	        return;

	    if (direction == 1) {
	        //如果当前页是倒数第二页，则将下一页设置为尾页
	        if (currentPageIndex == arrayLength - 2) {
	            $(modalSelect + " " + ".next-page").text("提交");
	        }

	        //如果当前页是首页，添加上一页
	        if (currentPageIndex == 0 && arrayLength > 1) {
	            $(modalSelect + " " + ".previous-page").removeClass("hidden");
	        }
	        //更换modal-body和页码
	        $(modalSelect + " " + ".page-index").text((++currentPageIndex).toString());
	        $(modalSelect + " " + ".modal-body").html(modalDataArray[currentPageIndex]);
	    }
	    else {
	        //如果当前页是尾页
	        if (currentPageIndex == arrayLength - 1) {
	            $(modalSelect + " " + ".next-page").text("下一页");
	        }

	        //如果当前页是正数第二页,则将上一页设置为首页
	        if (currentPageIndex == 1) {
	            $(modalSelect + " " + ".previous-page").addClass("hidden");
	        }
	        //更换modal-body和页码
	        $(modalSelect + " " + ".page-index").text((--currentPageIndex).toString());
	        $(modalSelect + " " + ".modal-body").html(modalDataArray[currentPageIndex]);
	    }

	}
	
	/**
	 *
	 * @param modalSelect modal选择符
	 * @param modalDataArray html代码字符串数组
	 * @param modalCallback modal回调函数
	 */
	function moadlDataControl(modalSelect, modalDataArray, modalCallback) {
	    //初始化模态框首页数据
	    $(modalSelect + " " + ".modal-body").html(modalDataArray[0]);
	    if (modalDataArray.length <= 1) {
	        $(modalSelect + " " + ".next-page").text("提交");
	    }

	    //点击下一页
	    $(modalSelect + " " + ".next-page").click(function () {
	        //调用回调函数
	        modalCallback();
	        if (cellRoomName == undefined) {
	            alert("请先选择使用会议室时间段！");
	            return;
	        }
	        if ($(this).text() == "提交") {
	        	if("1"==""){
	    			alert("请先选择参加人员！");
	                return;
	    		}
	        	var allPeoId = "";
	        	$("iframe").contents().find('#selectPage .content .weui-check__label').each(
						function(index, el) {
							allPeoId += $(this).attr("peoId") +",";
						});
	        	addMeeting(allPeoId.substring(0, allPeoId.length-1));
	            return;
	        }
	        //获取当前页码
	        var currentPageIndex = parseInt($(modalSelect + " " + ".page-index").text());
	        controlPageToggle(modalSelect, modalDataArray, currentPageIndex, 1);
	    });

	    //点击上一页
	    $(modalSelect + " " + ".previous-page").click(function () {
	        //获取当前页码
	        var currentPageIndex = parseInt($(modalSelect + " " + ".page-index").text());
	        controlPageToggle(modalSelect, modalDataArray, currentPageIndex, -1);
	        tableAction();
	    });

	    //关闭模态框时，重置为首页
	    $(modalSelect).on('hidden.bs.modal', function () {
	        $(modalSelect + " " + ".page-index").text((0).toString());
	        if (modalDataArray.length <= 1) {
	            $(modalSelect + " " + ".next-page").text("提交");
	        }
	        else {
	            $(modalSelect + " " + ".next-page").text("下一页");
	        }
	        $(modalSelect + " " + ".modal-body").html(modalDataArray[0]);
	        $(modalSelect + " " + ".previous-page").addClass("hidden");
	    })
	}
	
	function modalCallback() {
		
	}


</script>
</head>
<body>
	<div id="calendar"></div>
	<!-- <div class="am-modal am-modal-confirm" tabindex="-1" id="modal-event">
		<div class="am-modal-dialog">
			<div id="meeting-content"></div>
		</div>
	</div> -->
	
	<div id="myModal" class="modal fade"  tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" style="height: 1000px;">
        <div class="modal-dialog" >
        <div class="modal-content" >
            <div class="modal-header">
            	<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                <h4 class="modal-title" id="myModalLabel">预定会议室</h4>
            </div>
        <div class="modal-body">
			
		</div>
		<div class="modal-footer">
				<button type='button' class='btn btn-primary previous-page hidden'>
		                    上一页
		                </button>
		                <button type="button" class="btn btn-primary next-page">
		                    下一页
		                </button>
		                <button type="button" class="btn btn-default" data-dismiss="modal">
		                    取消
		                </button>
		                <label class="page-index" hidden>0</label>
			<!-- <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
			<button type="button" class="btn btn-primary" onclick="addMeeting();">预订</button> -->
		</div>
    </div>
    </div>
    </div>
    <input type="hidden" name="hiddenid" id="hiddenid"/>
    <div id="modal-event" class="modal fade"  tabindex="-1" role="dialog" aria-labelledby="myModalLabelD" aria-hidden="true">
        <div class="modal-dialog">
	        <div class="modal-content" id = "meeting-content">
	        	
	    	</div>
    	</div>
    </div>
    
    
    <div class="hidden" id ="tableDiv">
		<table border="1" id = "meetingRoomsTable">
				<tr>
			        <th width="12%">会议室名称</th>
					<th colspan="2" width="2%">10:00</th>
					<th colspan="2" width="2%">11:00</th>
					<th colspan="2" width="2%">12:00</th>
					<th colspan="2" width="2%">13:00</th>
					<th colspan="2" width="2%">14:00</th>
					<th colspan="2" width="2%">15:00</th> 
					<th colspan="2" width="2%">16:00</th>                    
					<th colspan="2" width="2%">17:00</th>      
					<th colspan="2" width="2%">18:00</th>   
					<th colspan="2" width="2%">19:00</th>
				</tr>
			    <tr id ="r1" data-room-name="会议室1">
			        <td>会议室1</td>
			        
			        <td class="meeting-cell mavailab" data-time="10:00" width="1%"></td>
			        <td class="meeting-cell mavailab" data-time="10:30" width="1%"></td>
			        <td class="meeting-cell mavailab" data-time="11:00" width="1%"></td>
			        <td class="meeting-cell mavailab" data-time="11:30" width="1%"></td>
			        <td class="meeting-cell mavailab" data-time="12:00" width="1%"></td>
					<!-- <td class="meeting-cell busy" data-href="/meetings/JsuCGgCnvs3yA6xGt3ML1s/go" colspan="2" data-am-popover="{content: 'ttt(sss)', trigger: 'hover focus'}" width="2%"></td> -->
			        <td class="meeting-cell mavailab" data-time="12:30" width="1%"></td>
			        <td class="meeting-cell mavailab" data-time="13:00" width="1%"></td>
			        <td class="meeting-cell mavailab" data-time="13:30" width="1%"></td>
			        <td class="meeting-cell mavailab" data-time="14:00" width="1%"></td>
			        <td class="meeting-cell mavailab" data-time="14:30" width="1%"></td>
			        <td class="meeting-cell mavailab" data-time="15:00" width="1%"></td>
			        <td class="meeting-cell mavailab" data-time="15:30" width="1%"></td>
			        <td class="meeting-cell mavailab" data-time="16:00" width="1%"></td>
			        <td class="meeting-cell mavailab" data-time="16:30" width="1%"></td>
			        <td class="meeting-cell mavailab" data-time="17:00" width="1%"></td>
			        <td class="meeting-cell mavailab" data-time="17:30" width="1%"></td>
			        <td class="meeting-cell mavailab" data-time="18:00" width="1%"></td>
			        <td class="meeting-cell mavailab" data-time="18:30" width="1%"></td>
			        <td class="meeting-cell mavailab" data-time="19:00" width="1%"></td>
			        <td class="meeting-cell mavailab" data-time="19:30" width="1%"></td>
			                                                                                                                                                                           
			    </tr>
			    <tr id ="r2" data-room-name="会议室2">
			        <td>会议室2</td>
			        
			        <td class="meeting-cell mavailab" data-time="10:00" width="1%"></td>
			        <td class="meeting-cell mavailab" data-time="10:30" width="1%"></td>
			        <td class="meeting-cell mavailab" data-time="11:00" width="1%"></td>
			        <td class="meeting-cell mavailab" data-time="11:30" width="1%"></td>
			        <td class="meeting-cell mavailab" data-time="12:00" width="1%"></td>
					<!-- <td class="meeting-cell busy" data-href="/meetings/JsuCGgCnvs3yA6xGt3ML1s/go" colspan="2" data-am-popover="{content: 'ttt(sss)', trigger: 'hover focus'}" width="2%"></td> -->
			        <td class="meeting-cell mavailab" data-time="12:30" width="1%"></td>
			        <td class="meeting-cell mavailab" data-time="13:00" width="1%"></td>
			        <td class="meeting-cell mavailab" data-time="13:30" width="1%"></td>
			        <td class="meeting-cell mavailab" data-time="14:00" width="1%"></td>
			        <td class="meeting-cell mavailab" data-time="14:30" width="1%"></td>
			        <td class="meeting-cell mavailab" data-time="15:00" width="1%"></td>
			        <td class="meeting-cell mavailab" data-time="15:30" width="1%"></td>
			        <td class="meeting-cell mavailab" data-time="16:00" width="1%"></td>
			        <td class="meeting-cell mavailab" data-time="16:30" width="1%"></td>
			        <td class="meeting-cell mavailab" data-time="17:00" width="1%"></td>
			        <td class="meeting-cell mavailab" data-time="17:30" width="1%"></td>
			        <td class="meeting-cell mavailab" data-time="18:00" width="1%"></td>
			        <td class="meeting-cell mavailab" data-time="18:30" width="1%"></td>
			        <td class="meeting-cell mavailab" data-time="19:00" width="1%"></td>
			        <td class="meeting-cell mavailab" data-time="19:30" width="1%"></td>
			    </tr>
			  </table>
	</div>
	
	<div class="hidden" id ="deviceDiv">
		<iframe id="NoPermissioniframe" width="100%" height="400px" frameborder="0" src ="<%=request.getContextPath()%>/device.do"></iframe>
	</div>
<jsp:include page="Footer.jsp"></jsp:include>
</body>
</html>
